package com.xzh.springCloud.service.impl;

import com.xzh.springCloud.dao.OrderDao;
import com.xzh.springCloud.entity.Order;
import com.xzh.springCloud.service.AccountService;
import com.xzh.springCloud.service.OrderService;
import com.xzh.springCloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
* @Author: zhiHong
* @CreateTime: 2023-09-01 11:03
* @Description:
*/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    @Resource
    private StorageService storageService;

    @Resource
    private AccountService accountService;

    /**
     * 1. @GlobalTransactional：分布式全局事务控制注解
     * 2. 参数 name 由程序员自己指定，但是需要保证唯一性
     * 3. 参数 rollbackFor 指定发生什么异常就进行回滚
     */
    @GlobalTransactional(name = "my-save-order", rollbackFor = Exception.class)
    @Override
    public void save(Order order) {
        // 1. 调用本地方法生成订单 order
        orderDao.save(order);
        // 2. 远程调用 storage 微服务扣减库存
        storageService.reduce(order.getProductId(), order.getNums());
        // 3. 远程调用 account 微服务扣减用户余额
        accountService.reduce(order.getUserId(), order.getMoney() * order.getNums());
        // 4. 调用本地方法修改订单状态 0 -> 1
        orderDao.update(order.getUserId(), 0);
    }
}
